﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace SunrayEngine.Maps
{
    /// <summary>
    /// A node in the SunRay Engine quad tree
    /// </summary>
    public class QuadNode
    {
        #region fields
        private QuadNode parent; //The parent node null if root
        private Rectangle bounds; //The bounds of the rectangle
        private int x; //The x-axis position of the node
        private int y; //The y-axis position of the node
        private float width; //The node width
        private float height; //The node height
        private QuadNode[] childs; //The childs of the node
        private bool isLeaf; //Determinates if the parent is at prefered size and 
                             //should not have any childs.
                             //This is also the node level that is used to retrive data.
        #endregion

        #region properties
        /// <summary>
        /// Returns the nodes bounds.
        /// </summary>
        public Rectangle Bounds { get { return bounds; } }
        #endregion

        #region initialization
        public QuadNode(int x, int y, float width, float height, QuadNode parent)
        {
            //Set parameters.
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
            bounds = new Rectangle(x, y, (int)width, (int)height);

            //Determin if this node is a parent.
            if (parent != null)
                this.parent = parent;

            //Determin if this node is a leaf.
            isLeaf = width <= 4 || height <= 4;

            //If this node is not a leaf we let it create
            //childs.
            if (!isLeaf)
            {
                childs = new QuadNode[4];
                childs[0] = new QuadNode(x, y, width * .5f, height * .5f, this);
                childs[1] = new QuadNode(x, y + (int)(width * .5f), width * .5f, height * .5f, this);
                childs[2] = new QuadNode(x + (int)(height * .5f), y, width * .5f, height * .5f, this);
                childs[3] = new QuadNode(x + (int)(height * .5f), y + (int)(width * .5f), width * .5f, height * .5f, this);
            }
        }
        #endregion
    }
}
